import heapq
import json

from querier.esquerier import ElasticSearchQuerier
import querier.weibo.utils as utils
# from utils import utils as uc

MAX_BRANDS = 100


class WeiboKOLInfoWithBrandQuerier(ElasticSearchQuerier):
    def _build_query(self, args):
        pass

    def _build_result(self, es_result, param):
        pass

    def __init__(self, kol_info, brand_match):
        super(WeiboKOLInfoWithBrandQuerier, self).__init__(None, None, None)
        self.kol_info = kol_info
        self.brand_match = brand_match

    def search(self, args):
        id_ = args.get('user_id')
        ids_ = args.get('user_ids')
        # result = []
        if id_ is None and ids_ is None:
            raise ValueError('message: "user_id" or "user_ids"(list of "user_id") is needed')

        if id_:
            return self.get_info(id_)
        else:
            result = [self.get_info(i) for i in ids_]

        kol_result = {"infos": result}
        return kol_result

    def get_info(self, id_):
        kol_info_args = {"user_id": id_}
        kol_result = self.kol_info.search(kol_info_args)
        keywords = kol_result.get('keywords', [])
        kol_result['ex_brands'] = self.get_brands(keywords)
        return kol_result

    def get_brands(self, keywords):
        args = {
            'term': ' '.join(keywords),
            'from': 0,
            'size': MAX_BRANDS
        }
        brand_result = self.brand_match.search(args)
        brands = [b.get('brand', '') for b in brand_result.get('brands', [])]
        weights = [b.get('score', '') for b in brand_result.get('brands', [])]
        brands = utils.get_kv_json(brands, weights)
        return brands


class WeiboKOLInfoQuerier(ElasticSearchQuerier):

    def __init__(self, es, index, doc_type):
        super(WeiboKOLInfoQuerier, self).__init__(None, None, None)
        self.es = es
        self.index = index
        self.doc_type = doc_type

    def search(self, args):
        id_ = args['user_id']
        if not id_:
            return {"message": "user_id is needed"}
        try:
            res = self.es.get(index=self.index, doc_type=self.doc_type, id=id_)
        except Exception as e:
            return {'message': "Error %s" % str(e)}
        return self._build_result(res, None)

    def _build_result(self, es_result, param):
        if es_result['found']:
            source_ = es_result['_source']
            return utils.extract_user_from_source(source_)

    def _build_query(self, args):
        ids = args.get('user_id')
        if ids is None:
            raise ValueError('message: "weibo_ids"(list of "weibo_id") is needed')

        query = {"query": {"terms": {"user_id": ids}}, "size": 1000}
        return query, {}, {'weibo_ids': ids}

    # def _build_result(self, es_result, param):
    #     ids = param['weibo_ids']
    #     articles = []
    #     for hit in es_result['hits']['hits']:
    #         data = self.extract_result(hit)
    #         articles.append((data.get('weibo_id'), data))
    #     article_dict = dict(articles)
    #     return {
    #         "infos": [article_dict.get(i, {}) for i in ids]
    #     }


